package com.mytrip.util;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;

import com.mytrip.service.BackOperatorManager;
import com.mytrip.webapp.filter.CtxSessionBag;

public class LoginUtil {
	public static final String COMMON_LOGIN_COOKIE = "commonLoginCookie";
	public static final String DOMAIN = ".mytrip.com";
	public static boolean validateCookie() {
		CookieWrapper cookieWrapper = new CookieWrapper(ServletActionContext.getRequest(), ServletActionContext.getResponse());
		Cookie cookieCommon = cookieWrapper.getCookie(COMMON_LOGIN_COOKIE);
		if (cookieCommon == null) {
			return false;
		} 
		if(!cookieCommon.getValue().equals(CtxSessionBag.getSessionBag().getBackOperatorCookieValue())) {
			String[] splits;
			try {
				splits = Encrypter.decrypt(cookieCommon.getValue()).split(";", 4);
			} catch (RuntimeException e) {
				return false;
			}
			BackOperatorManager backOperatorManager = (BackOperatorManager) SpringUtil.getBackendBean("backOperatorManager");
			if(splits.length!=4||!getRequestIp().equals(splits[3])||backOperatorManager.login(splits[0], splits[1], Integer.parseInt(splits[2]))==null) {
				return false;
			}
		}
		return true;
	}
	private static String getRequestIp() {
		String ip = ServletActionContext.getRequest().getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip=ServletActionContext.getRequest().getRemoteAddr();
		}
		return ip;
	}
	
	public static void saveCookie(String userName, String password, Integer defaultAdminSiteId) {
		CookieWrapper cookieWrapper = new CookieWrapper(ServletActionContext.getRequest(), ServletActionContext.getResponse());
		String ip = getRequestIp();
		String orgStr=userName + ";" + password + ";" + defaultAdminSiteId + ";" + ip;
		String str = Encrypter.encrypt(orgStr);
		String memcacheKey = SessionMemcacheUtil.getRandomMemcacheKey();
		CtxSessionBag.getSessionBag().setBackOperatorCookieValue(str);
		CtxSessionBag.getSessionBag().setMemcacheKey(memcacheKey);
		cookieWrapper.setCookie(COMMON_LOGIN_COOKIE, str, DOMAIN);
		cookieWrapper.setCookie(SessionMemcacheUtil.COOKIE_SESSION_KEY, memcacheKey, DOMAIN);
	}

	public static void clearCookie() {
		CookieWrapper cookieWrapper = new CookieWrapper(ServletActionContext.getRequest(), ServletActionContext.getResponse());
		cookieWrapper.setCookie(COMMON_LOGIN_COOKIE,null, DOMAIN);
		cookieWrapper.setCookie(SessionMemcacheUtil.COOKIE_SESSION_KEY, null, DOMAIN);
	}
}
